# encoding:utf-8
# getdata就是查询得到的数据，SQL查询得到的是一个数组，但是需要程序自己判断是否为空，为空是否要报错
# 脚本执行完成后的的data:{}会被放到name的位置。
import sys
import json
import datetime
import re
from collections import defaultdict
from datetime import datetime

def format_servers_info(json_data):
    data = json_data.get('data', {})
    zone = json_data.get('param', {}).get('zone', '未知区域')
    servers_info = []

    # 处理选中的组（排除空数据中心和未分组服务器）
    for group_id in data:
        if group_id in ["empty_data_centers", "no_group_servers"]:
            continue
        group_info = data.get(group_id, {})
        # 处理空组或仅有detail的组
        if not group_info or ("detail" in group_info and len(group_info) == 1):
            department_name = group_id
            if "detail" in group_info:
                department_name = group_info["detail"].get("name", group_id)
                department_time = group_info["detail"].get("time", group_id)
            serverinfo = {
                "zone": zone,
                "serverType": "",
                "serverModel": "",
                "serverGroupId": group_id,
                "serverId": "",
                "serverIp": "",
                "serverBmcAddress": "",
                "DepartmentName": department_name,
                "DepartmentCreateTime": department_time,
                "serverDataCenterName": "",
                "serverDataCenterId": "",
                "serverDataCenterLocation": "",
                "serverStatus": 3,
                "serverCpuNpuType": "",
                "serverCpuNpuModel": "",
                "cpuMonitorData": {},
                "serverCpuNpuCount": 0,
                "departmentStatus": "empty",
                "machineRoomName": "",
                "machineRoomId": "",
            }
            servers_info.append(serverinfo)
            continue
        # 处理组内服务器
        for machine_id, machine_info in group_info.items():
            if machine_id == "detail":
                continue
            serverinfo = {
                "zone": zone,
                "serverType": machine_info.get("server_model", ""),
                "serverModel": machine_info.get("server_model", ""),
                "serverGroupId": group_id,
                "serverId": machine_id,
                "serverIp": machine_info.get("bmc_ip", ""),
                "serverBmcAddress": machine_info.get("bmc_ip", ""),
                "DepartmentName": machine_info.get("asset_group_name", ""),
                "DepartmentCreateTime": machine_info.get("asset_group_create_time", ""),
                "serverDataCenterName": machine_info.get("data_center_name", ""),
                "serverDataCenterId": machine_info.get("data_center_id", ""),
                "serverDataCenterLocation": (
                    f"{machine_info.get('data_center_province', '')}"
                ) if (machine_info.get('data_center_province')) else "未录入数据中心",
                "serverStatus": machine_info.get("resource_health_state", 0),
                "serverCpuNpuType": machine_info.get("cpu_npu_type", "其他"),
                "serverCpuNpuModel": machine_info.get("cpu_npu_model", ""),
                "cpuMonitorData": machine_info.get("CPU", {}),
                "serverCpuNpuCount": int(machine_info.get("cpu_npu_count", 0)),
                "machineRoomName": machine_info.get("machine_room_name", "未录入机房"),
                "machineRoomId": machine_info.get("machine_room_id", ""),
                "departmentStatus": ""  # 正常服务器无状态标识
            }
            servers_info.append(serverinfo)

    # 处理空数据中心
    empty_dcs = data.get("empty_data_centers", {}).get("empty_data_centers", [])
    for dc in empty_dcs:
        province = dc.get("province", "")
        city = dc.get("city", "")
        location = f"{province}" if province else "未录入数据中心"
        servers_info.append({
            "zone": zone,
            "serverType": "",
            "serverModel": "",
            "serverGroupId": "",
            "serverId": "",
            "serverIp": "",
            "serverBmcAddress": "",
            "DepartmentName": "",
            "DepartmentCreateTime": "",
            "serverDataCenterName": dc.get("data_center_name", ""),
            "serverDataCenterId": dc.get("data_center_id", ""),
            "serverDataCenterLocation": location,
            "serverStatus": 3,
            "serverCpuNpuType": "",
            "serverCpuNpuModel": "",
            "cpuMonitorData": {},
            "serverCpuNpuCount": 0,
            "departmentStatus": "empty_data_center",
            "machineRoomName": "",
            "machineRoomId": "",
        })

    # 处理未分组的服务器（新格式：直接以机器ID为键的字典）
    no_group_servers = data.get("no_group_servers", {})  # 直接获取字典
    for machine_id, machine_info in no_group_servers.items():
        serverinfo = {
            "zone": zone,
            "serverType": machine_info.get("server_model", ""),
            "serverModel": machine_info.get("server_model", ""),
            "serverGroupId": "",  # 无关联组
            "serverId": machine_id,
            "serverIp": machine_info.get("bmc_ip", ""),
            "serverBmcAddress": machine_info.get("bmc_ip", ""),
            "DepartmentName": machine_info.get("asset_group_name", "未录入部门"),  # 保留原有字段
            "DepartmentCreateTime": machine_info.get("asset_group_create_time", ""),
            "serverDataCenterName": machine_info.get("data_center_name", ""),
            "serverDataCenterId": machine_info.get("data_center_id", ""),
            "serverDataCenterLocation": (
                f"{machine_info.get('data_center_province', '')}"
            ) if (machine_info.get('data_center_province')) else "未录入数据中心",
            "serverStatus": machine_info.get("resource_health_state", 0),
            "serverCpuNpuType": machine_info.get("cpu_npu_type", "其他"),
            "serverCpuNpuModel": machine_info.get("cpu_npu_model", ""),
            "cpuMonitorData": machine_info.get("CPU", {}),
            "serverCpuNpuCount": int(machine_info.get("cpu_npu_count", 0)),
            "machineRoomName": machine_info.get("machine_room_name", "未录入机房"),
            "machineRoomId": machine_info.get("machine_room_id", ""),
            "departmentStatus": "no_group"  # 状态标识
        }
        servers_info.append(serverinfo)

    return servers_info

def get_all_departments_server_info(servers_info):
    # 首先过滤掉空数据中心，但保留所有部门（包括只有无效服务器的部门）
    filtered_servers = [s for s in servers_info if s.get("departmentStatus") != "empty_data_center"]

    has_department = []
    no_group_servers = []

    for s in filtered_servers:
        if s.get("departmentStatus") == "no_group":
            no_group_servers.append(s)
        else:
            has_department.append(s)

    # 处理正常部门分组
    all_departments = {}
    for server in has_department:
        group_id = server["serverGroupId"]
        if group_id not in all_departments:
            all_departments[group_id] = []
        all_departments[group_id].append(server)

    # 初始化统计指标
    total_department_num = len(all_departments)
    total_servers = 0  # 初始化为0，后面会累加有效服务器
    total_offline = 0
    total_err = 0
    department_details = {}

    # 处理每个部门
    for group_id, servers in all_departments.items():
        # 检查部门是否为空或只有无效服务器
        valid_servers = [s for s in servers
                         if not s.get("departmentStatus")
                         and s.get("serverCpuNpuCount", 0) > 0]

        if servers[0].get("departmentStatus") == "empty" or len(valid_servers) == 0:
            # 空部门或只有无效服务器的部门处理
            department_details[group_id] = {
                "departmentName": servers[0].get("DepartmentName", group_id),
                "departmentServerNum": 0,
                "departmentServerCPUAverageUtils": "-",
                "errServerNum": 0,
                "offlineServerNum": 0,
                "yellowZoneServerNum": 0,
                "blueZoneServerNum": 0,
                "departmentCreateTime": servers[0].get("DepartmentCreateTime", "")
            }
        else:
            # 正常部门统计
            offline = sum(1 for s in valid_servers if s["serverStatus"] in {0, 2})
            errors = sum(1 for s in valid_servers if s["serverStatus"] in {1, 3})
            cpu_utils = [s["cpuMonitorData"]["server_average_cpu_util"]
                         for s in valid_servers if s["cpuMonitorData"].get("server_average_cpu_util")]

            avg_cpu = round(sum(cpu_utils) / len(cpu_utils), 2) if cpu_utils else "-"
            yellow = sum(1 for s in valid_servers if s["zone"] == "yellow")
            blue = sum(1 for s in valid_servers if s["zone"] == "blue")

            department_details[group_id] = {
                "departmentName": valid_servers[0]["DepartmentName"],
                "departmentServerNum": len(valid_servers),
                # "departmentServerCPUAverageUtils": avg_cpu,
                "departmentServerCPUAverageUtils": f"{avg_cpu:.2f}" if isinstance(avg_cpu, (int, float)) else "-",
                "errServerNum": errors,
                "offlineServerNum": offline,
                "yellowZoneServerNum": yellow,
                "blueZoneServerNum": blue,
                "departmentCreateTime": valid_servers[0].get("DepartmentCreateTime", "")
            }
            total_servers += len(valid_servers)
            total_offline += offline
            total_err += errors

    def adjust_microseconds(iso_time):
        # 正则表达式匹配小数点后的微秒部分和时区部分
        pattern = r'\.(\d+)([+-]\d{2}:\d{2})$'
        match = re.search(pattern, iso_time)
        if match:
            microseconds = match.group(1)
            timezone = match.group(2)
            # 补足微秒部分到6位
            adjusted_microseconds = microseconds.ljust(6, '0')[:6]
            adjusted_time = re.sub(pattern, f'.{adjusted_microseconds}{timezone}', iso_time)
            return adjusted_time
        return iso_time

    def iso_to_non_tz_time(iso_time):
        if not iso_time:
            return ""
        # 调整时间字符串的微秒部分
        adjusted_time = adjust_microseconds(iso_time)
        # 解析为datetime对象
        dt = datetime.fromisoformat(adjusted_time)
        # 格式化为不带时区的字符串
        return dt.strftime("%Y-%m-%d %H:%M:%S.%f")

    # 构建排序后的结果
    sorted_departments = sorted(
        department_details.values(),
        key=lambda x: datetime.strptime(iso_to_non_tz_time(x["departmentCreateTime"]), "%Y-%m-%d %H:%M:%S.%f")
        if x["departmentCreateTime"] else datetime.min,
        reverse=True
    )

    # 计算全局CPU平均值（仅统计有效部门）
    valid_deps = [d for d in department_details.values()
                  if d["departmentServerCPUAverageUtils"] != "-"]

    if not valid_deps:
        avg_util = "-"
    else:
        avg_util = round(sum(float(d["departmentServerCPUAverageUtils"]) for d in valid_deps) / len(valid_deps),
                     2) if valid_deps else 0.0

    return {
        "allDepartmentServerSummary": {
            "departmentNum": total_department_num,
            "totalServerNum": total_servers,
            "offlineServerNum": total_offline,
            "errServerNum": total_err,
            "departmentAverageUtil": f"{avg_util:.2f}" if isinstance(avg_util, (int, float)) else "-",
        },
        "allDepartmentServerStaticInfo": sorted_departments
    }

def get_gen_usage(raw_cpu_model):
    pattern_1 = r"(?i)intel\(r\) xeon\(r\) (platinum|gold|bronze|silver) \d1.*|xeon_gold_61.*"  # 第二个数字是1
    pattern_2 = r"(?i)intel\(r\) xeon\(r\) (platinum|gold|bronze|silver) \d2.*"  # 第二个数字是2
    pattern_3 = r"(?i)intel\(r\) xeon\(r\) (platinum|gold|bronze|silver) \d3.*"  # 第二个数字是3
    pattern_45 = r"(?i)intel\(r\) xeon\(r\) (platinum|gold|bronze|silver) \d[45].*|xeon_platinum_84.*"  # 第二个数字是4或5
    processor_name = "其他"
    if re.match(pattern_1, raw_cpu_model):
        processor_name = "Intel Gen1"
    elif re.match(pattern_2, raw_cpu_model):
        processor_name = "Intel Gen2"
    elif re.match(pattern_3, raw_cpu_model):
        processor_name = "Intel Gen3"
    elif re.match(pattern_45, raw_cpu_model):
        processor_name = "Intel Gen4-5"
    return processor_name


def get_all_servers_type_static_info(servers_info):
    servers_total_processors_list = []
    servers_types_list = []
    format_servers_type_info = []

    for server_info in servers_info:
        department_status = server_info.get("departmentStatus")
        if department_status in ["empty", "empty_data_center"]:
            continue

        server_processor_model = server_info.get("serverCpuNpuModel")
        server_processor_type = server_info.get("serverCpuNpuType")
        server_cpu_npu_count = server_info.get("serverCpuNpuCount", 0)

        if server_processor_type == "cpu":
            server_info["serverCalculateType"] = "通用计算型"
            if "通用计算型" not in servers_types_list:
                servers_types_list.append("通用计算型")
            if not server_processor_model:
                cpu_new_model = "其他"
            elif "AMD EPYC" in server_processor_model:
                cpu_new_model = "AMD EPYC"
            elif re.match(r"(?i)huawei kunpeng", server_processor_model):
                cpu_new_model = "Kunpeng"
            elif re.match(r"(?i)intel\(r\)|xeon_gold_61.*|xeon_platinum_84.*", server_processor_model):
                cpu_new_model = get_gen_usage(server_processor_model)
            else:
                cpu_new_model = "其他"
            servers_total_processors_list.append(cpu_new_model)
            server_info["serverCpuNpuModel"] = cpu_new_model
        elif server_processor_type in ["npu", "gpu"]:
            server_info["serverCalculateType"] = "AI加速型"
            if "AI加速型" not in servers_types_list:
                servers_types_list.append("AI加速型")
            if server_processor_type == "npu":
                if not server_processor_model or not re.match(r"(?i)ascend.*", server_processor_model):
                    npu_new_model = "其他 NPU"
                else:
                    npu_new_model = "昇腾 NPU"
                servers_total_processors_list.append(npu_new_model)
                server_info["serverCpuNpuModel"] = npu_new_model
            else:  # gpu
                if not server_processor_model or not re.match(r"(?i)nvidia.*", server_processor_model):
                    gpu_new_model = "其他 GPU"
                else:
                    gpu_new_model = "Nvidia GPU"
                servers_total_processors_list.append(gpu_new_model)
                server_info["serverCpuNpuModel"] = gpu_new_model
        else:
            continue  # 直接跳过不符合条件的服务器

        format_servers_type_info.append(server_info)

    # 计算总体平均利用率
    processor_type_avg_utils = {}
    for server_info in format_servers_type_info:
        processor_type = server_info["serverCpuNpuModel"]
        avg_util = server_info.get("cpuMonitorData", {}).get("server_average_cpu_util")
        if avg_util is not None:
            if processor_type not in processor_type_avg_utils:
                processor_type_avg_utils[processor_type] = []
            processor_type_avg_utils[processor_type].append(avg_util)

    processor_type_averages = [sum(utils) / len(utils) for utils in processor_type_avg_utils.values() if utils]
    overall_avg = round(sum(processor_type_averages) / len(processor_type_averages),
                        2) if processor_type_averages else "-"

    # 按服务器类型分组
    server_type_servers_info = {}
    for server_info in format_servers_type_info:
        server_type = server_info["serverCalculateType"]
        if server_type not in server_type_servers_info:
            server_type_servers_info[server_type] = []
        server_type_servers_info[server_type].append(server_info)

    # 对每个类型下的服务器按数量排序
    for server_type, servers in server_type_servers_info.items():
        servers.sort(key=lambda x: x.get("serverCpuNpuCount", 0))

    # 按类型顺序处理：通用计算型 -> AI加速型
    sorted_server_types = []
    if "通用计算型" in server_type_servers_info:
        sorted_server_types.append("通用计算型")
    if "AI加速型" in server_type_servers_info:
        sorted_server_types.append("AI加速型")

    processor_servers_static_info = {}
    for server_type in sorted_server_types:
        servers = server_type_servers_info[server_type]
        processor_name_groups = {}

        for server in servers:
            model = server["serverCpuNpuModel"]
            if model not in processor_name_groups:
                processor_name_groups[model] = []
            processor_name_groups[model].append(server)

        for model, group in processor_name_groups.items():
            total = len(group)
            offline = sum(1 for s in group if s.get("serverStatus", 0) in [0, 2])
            err = sum(1 for s in group if s.get("serverStatus", 0) in [1, 3])
            utils = [s.get("cpuMonitorData", {}).get("server_average_cpu_util")
                     for s in group if s.get("cpuMonitorData", {}).get("server_average_cpu_util") is not None]

            avg_util = round(sum(utils) / len(utils), 2) if utils else "-"

            entry = {
                "processorName": model,
                "processorTotalServerNum": total,
                "processorServerCPUAverageUtils": f"{avg_util:.2f}" if isinstance(avg_util, (int, float)) else "-",
                "processorServerState": {
                    'offlineServerNum': offline,
                    'errServerNum': err
                }
            }
            if server_type not in processor_servers_static_info:
                processor_servers_static_info[server_type] = []
            processor_servers_static_info[server_type].append(entry)

    # 构建最终结果
    zone = format_servers_type_info[0].get("zone") if format_servers_type_info else None

    all_server_type_static_info = []
    total_err = 0
    total_offline = 0

    for server_type in sorted_server_types:
        for proc_info in processor_servers_static_info.get(server_type, []):
            total_err += proc_info["processorServerState"]["errServerNum"]
            total_offline += proc_info["processorServerState"]["offlineServerNum"]

            all_server_type_static_info.append({
                "serverType": server_type,
                "processorName": proc_info["processorName"],
                "processorTotalServerNum": proc_info["processorTotalServerNum"],
                "offlineServerNum": proc_info["processorServerState"]["offlineServerNum"],
                "errServerNum": proc_info["processorServerState"]["errServerNum"],
                "yellowZoneServerNum": proc_info["processorTotalServerNum"] if zone == "yellow" else 0,
                "blueZoneServerNum": proc_info["processorTotalServerNum"] if zone == "blue" else 0,
                "processorServerCPUAverageUtils": proc_info["processorServerCPUAverageUtils"]
            })

    servers_static_data = {
        "serverTypeSummary": {
            "serverTypeNum": len(servers_types_list),
            "processorTypeNum": len(set(servers_total_processors_list)),
            "errServerNum": total_err,
            "offlineServerNum": total_offline,
            "serverAverageUtil": f"{overall_avg:.2f}" if isinstance(overall_avg, (int, float)) else "-"
        },
        "allServerTypeStaticInfo": all_server_type_static_info
    }

    return servers_static_data


def get_province_servers_distribution(servers_info):
    # 初始化省份分布结构
    province_map = {}
    # 未录入数据中心统计
    no_dc_servers = {
        "total": 0,
        "offline": 0,
        "error": 0,
        "cpu_utils": []
    }
    # 判断zone类型
    yellow_zone, blue_zone = False, False
    if servers_info and servers_info[0].get("zone") == "yellow":
        yellow_zone = True
    elif servers_info and servers_info[0].get("zone") == "blue":
        blue_zone = True
    # 第一遍遍历：识别所有数据中心（包括只有无效服务器的）
    all_data_centers = set()
    for server in servers_info:
        # 检查是否是有效数据中心
        if all([server.get("serverDataCenterId"),
                server.get("serverDataCenterName"),
                server.get("serverDataCenterLocation")]):
            province = server.get("serverDataCenterLocation").strip()
            dc_name = server.get("serverDataCenterName").strip()
            all_data_centers.add((province, dc_name))
    # 第二遍遍历：建立三级结构（省份->数据中心->机房）并统计
    for server in servers_info:
        # 跳过空部门的服务器
        department_status = server.get("departmentStatus")
        if department_status == "empty":
            continue
        # 处理未录入数据中心的服务器
        if not all([server.get("serverDataCenterId"),
                    server.get("serverDataCenterName"),
                    server.get("serverDataCenterLocation")]):
            # 只有有效服务器才计入统计
            if server.get("serverCpuNpuCount", 0) > 0:
                no_dc_servers["total"] += 1
                if server["serverStatus"] in [0, 2]:
                    no_dc_servers["offline"] += 1
                elif server["serverStatus"] in [1, 3]:
                    no_dc_servers["error"] += 1
                if server.get("cpuMonitorData", {}).get("server_average_cpu_util") is not None:
                    no_dc_servers["cpu_utils"].append(server["cpuMonitorData"]["server_average_cpu_util"])
            continue
        # 获取数据中心信息
        province = server.get("serverDataCenterLocation").strip()
        dc_name = server.get("serverDataCenterName").strip()
        room_name = (server.get("machineRoomName") or "未录入机房").strip()
        # 初始化数据结构（不管服务器是否有效）
        province_data = province_map.setdefault(province, {
            "total": 0,
            "offline": 0,
            "error": 0,
            "cpu_utils": [],
            "datacenters": {}
        })
        dc_data = province_data["datacenters"].setdefault(dc_name, {
            "total": 0,
            "offline": 0,
            "error": 0,
            "cpu_utils": [],
            "machine_rooms": {}
        })
        # 只有有效服务器才初始化机房信息
        if server.get("serverCpuNpuCount", 0) > 0:
            room_data = dc_data["machine_rooms"].setdefault(room_name, {
                "total": 0,
                "offline": 0,
                "error": 0,
                "cpu_utils": []
            })
            # 更新统计量
            def update_counts(data_dict):
                data_dict["total"] += 1
                if server["serverStatus"] in [0, 2]:
                    data_dict["offline"] += 1
                elif server["serverStatus"] in [1, 3]:
                    data_dict["error"] += 1
                if server.get("cpuMonitorData", {}).get("server_average_cpu_util") is not None:
                    data_dict["cpu_utils"].append(server["cpuMonitorData"]["server_average_cpu_util"])
            update_counts(province_data)
            update_counts(dc_data)
            update_counts(room_data)
    # 处理空数据中心（包括只有无效服务器的）
    for (province, dc_name) in all_data_centers:
        if province not in province_map:
            province_map[province] = {
                "total": 0,
                "offline": 0,
                "error": 0,
                "cpu_utils": [],
                "datacenters": {}
            }
        if dc_name not in province_map[province]["datacenters"]:
            province_map[province]["datacenters"][dc_name] = {
                "total": 0,
                "offline": 0,
                "error": 0,
                "cpu_utils": [],
                "machine_rooms": {}  # 空数据中心不初始化机房信息
            }
    # 构建最终结构
    result = []
    for province_name, province_stats in province_map.items():
        if province_name == "黑龙江省":
            province_name = "黑龙江"
        elif province_name == "内蒙古自治区":
            province_name = "内蒙古"
        else:
            province_name = province_name[:2]
        dc_list = []
        for dc_name, dc_stats in province_stats["datacenters"].items():
            room_list = []
            # 只有有机房数据时才添加机房信息
            if dc_stats["machine_rooms"]:
                for room_name, room_stats in dc_stats["machine_rooms"].items():
                    room_avg = round(sum(room_stats["cpu_utils"]) / len(room_stats["cpu_utils"]), 2) if room_stats[
                        "cpu_utils"] else 0
                    room_list.append({
                        "dcServMaRoomName": room_name,
                        "dcServMaRoomServerNum": room_stats["total"],
                        "dcServMaRoomServerErrNum": room_stats["error"],
                        "dcServMaRoomServerOfflineNum": room_stats["offline"],
                        "yellowZoneServerNum": room_stats["total"] if yellow_zone else 0,
                        "blueZoneServerNum": room_stats["total"] if blue_zone else 0,
                        "dcServMaRoomServerUtil": room_avg
                    })
            # 计算数据中心的平均利用率（所有机房平均的平均）
            room_utils = [room["dcServMaRoomServerUtil"] for room in room_list]
            dc_avg = round(sum(room_utils) / len(room_utils), 2) if room_utils else 0
            dc_list.append({
                "dcName": dc_name,
                "dcServerNum": dc_stats["total"],
                "dcErrServerNum": dc_stats["error"],
                "dcOfflineServerNum": dc_stats["offline"],
                "yellowZoneServerNum": dc_stats["total"] if yellow_zone else 0,
                "blueZoneServerNum": dc_stats["total"] if blue_zone else 0,
                "dcServerAverageUtil": dc_avg,
                "dcServerMachineRoomInfo": room_list if room_list else []
            })
        # 计算省份的平均利用率（仅统计有服务器的数据中心）
        province_dc_utils = [dc["dcServerAverageUtil"] for dc in dc_list if dc["dcServerNum"] > 0]
        province_avg = round(sum(province_dc_utils) / len(province_dc_utils), 2) if province_dc_utils else 0
        result.append({
            "provinceName": province_name,
            "provinceServerNum": province_stats["total"],
            "offlineServerNum": province_stats["offline"],
            "errServerNum": province_stats["error"],
            "yellowZoneServerNum": province_stats["total"] if yellow_zone else 0,
            "blueZoneServerNum": province_stats["total"] if blue_zone else 0,
            "provinceServerAverageUtil": province_avg,
            "dataCenterInfo": dc_list
        })
    # 处理未录入数据中心数据
    no_dc_avg = round(sum(no_dc_servers["cpu_utils"]) / len(no_dc_servers["cpu_utils"]), 2) if no_dc_servers[
        "cpu_utils"] else 0
    no_dc_info = {
        "noEnterIntoTotalNum": no_dc_servers["total"],
        "noEnterIntoOfflineTotalNum": no_dc_servers["offline"],
        "noEnterIntoErrTotalNum": no_dc_servers["error"],
        "yellowZoneServerNum": no_dc_servers["total"] if yellow_zone else 0,
        "blueZoneServerNum": no_dc_servers["total"] if blue_zone else 0,
        "noEnterIntoServerAverageUtils": no_dc_avg
    } if no_dc_servers["total"] > 0 else {}
    return {
        "provinceServerDistribution": sorted(result, key=lambda x: x["provinceName"]),
        "noEnterIntoDataCenterInfo": no_dc_info
    }

def get_static_servers_info(raw_data=None):
    static_data = {}
    # 将原始数据格式化为服务器信息列表
    servers_info = format_servers_info(raw_data)
    # print(f"servers_info: {servers_info}")
    # 获取总体服务器信息
    all_calculate_summary = get_all_calculate_summary(servers_info)
    static_data.update(all_calculate_summary)
    # 根据服务器/处理器类型获取服务器统计信息
    servers_static_data = get_all_servers_type_static_info(servers_info)
    static_data.update(servers_static_data)
    # 获取数据中心的位置服务器统计信息
    province_servers_distribution = get_province_servers_distribution(servers_info)
    static_data.update(province_servers_distribution)
    # 获取所有部门的服务器统计信息
    department_static_data = get_all_departments_server_info(servers_info)
    static_data.update(department_static_data)
    return static_data

def get_all_calculate_summary(servers_info):
    # 初始化计数器
    total = 0
    offline = 0
    error = 0
    yellow = 0
    blue = 0

    # 遍历统计
    for server in servers_info:
        # 排除条件：
        # 1. 空数据中心或空部门
        # 2. 没有处理器的服务器
        department_status = server.get("departmentStatus")
        if department_status in ["empty", "empty_data_center"]:
            continue
        if server.get("serverCpuNpuCount", 0) <= 0:
            continue

        # 统计有效服务器
        total += 1

        # 区域统计
        zone = server.get("zone", "")
        if zone == "yellow":
            yellow += 1
        elif zone == "blue":
            blue += 1

        # 状态统计
        status = server.get("serverStatus", 0)
        if status in [0, 2]:  # 0:未知 2:离线
            offline += 1
        elif status in [1, 3]:  # 1:紧急 3:提示
            error += 1

    # 构建返回结构
    return {
        "allCalculateServerSummary": {
            "totalServerNum": total,
            "offlineServerNum": offline,
            "errServerNum": error,
            "yellowZoneServerNum": yellow,  # 实际黄区数量
            "blueZoneServerNum": blue  # 实际蓝区数量
        }
    }

def main():
    ret = {"code": 0, "message": "", "data": {}}
    if "data" not in jsondata:
        ret["code"] = 1
        ret["message"] = "操作失败"
        exit(0)
    rst_dict = {}
    servers_static_info_rst = get_static_servers_info(jsondata)
    rst_dict.update(servers_static_info_rst)

    ret["code"] = 0
    ret["message"] = "操作成功"
    ret["data"] = rst_dict
    return ret

if __name__ == '__main__':
    res = main()
    # print(json.dumps(res))
    print(json.dumps(res, ensure_ascii=False))

# 数据中心、BMCIP、密码